package com.javawork.juc.three;

import java.util.concurrent.TimeUnit;

/**
 * wait方法和notify方法，两个都去掉同步代码块; 异常情况
 * 将notify放在wait方法前面程序无法执行，无法唤醒,<br/>
 * wait和notify方法必须要在同步块或者方法里面，且成对出现使用先wait后notify才OK
 * @author zhangxiaolu
 * @since 2023-02-09 22:22
 */
public class ObjectWaitAndNotifyDemo {

    public static void main(String[] args) {
        Object olock = new Object();
        new Thread(() -> {
            synchronized (olock) {
                System.out.println(Thread.currentThread().getName() + "---come in");
                try {
                    olock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "------被唤醒");
            }
        }, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            synchronized (olock) {
                olock.notify();
                System.out.println(Thread.currentThread().getName() + "------发出唤醒");
            }
        }, "t2").start();
    }
}
